/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test.shashindra;

import com.googlecode.javacv.cpp.opencv_video.BackgroundSubtractorMOG2;
import com.googlecode.javacv.*;

import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import objectExtraction.HSVSkinDetector;

public class AutoBckSubCam implements Runnable {

    final int CAMERANO;
    final double CAMERAANGLE;
    CanvasFrame canvas = new CanvasFrame("Web Cam Live");
    CanvasFrame canvas1 = new CanvasFrame("Back Ground Subtracted");
    CanvasFrame canvas2 = new CanvasFrame("Skin Detected");
    int posX;
    int posY;

    public AutoBckSubCam(int cameraNo, double camAng) {
        super();
        this.CAMERANO = cameraNo;
        this.CAMERAANGLE = camAng;
        canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void run() {
        FrameGrabber grabber = new VideoInputFrameGrabber(CAMERANO);
        BackgroundSubtractorMOG2 mog = new BackgroundSubtractorMOG2(400, 8, true);
        HSVSkinDetector hs = new HSVSkinDetector();
        try {
            grabber.start();
            Thread.sleep(1000);
            IplImage img, foreground,skin;
            posY = 0;
            while (true) {
                img = grabber.grab();
                // BufferedImage img1=img.getBufferedImage();
                if (img != null) {
                    foreground = IplImage.create(img.width(), img.height(), IPL_DEPTH_8U, 1);
                    skin=hs.getHSVSkin(img);
                    canvas.showImage(img);
                    canvas2.showImage(skin);
                    mog.apply(img, foreground, -1);
                    cvThreshold(foreground, foreground, 128, 255, CV_THRESH_BINARY);
//                    cvDilate(foreground, foreground, null, 4);
//                    cvErode(foreground, foreground, null, 4);


                    IplConvKernel rect_6 = cvCreateStructuringElementEx(5, 5, 3, 3, CV_SHAPE_ELLIPSE, null);

                    cvMorphologyEx(foreground, foreground, foreground, rect_6, CV_MOP_CLOSE, 1);

                    canvas1.showImage(foreground);
                }
            }
        } catch (Exception e) {
        }

    }
}
